# coding:utf-8

import os
from color_print import printDarkYellow

"""
作者：雪山凌狐
网址：http://www.xueshanlinghu.com
修订时间：2020-07-12

写书好伴侣，自动目录生成器
目录需满足条件：
1.各个章节使用`chapter+章节`数字的方式来写，且每个文件夹里面都有一个README.md文件，文件第一行是一级标题的章节名
2.各课时md文件存放到各自的章节目录里面，课时的文件名跟需要生成的课时名一致，且文件名开头为章节数字-数字序号（如第一章第一节为 1-1），序号结束后空格后再写其他内容
3.章节的目录中除了assets文件夹以外不要有其他文件夹了

运行后会自动生成目录树和目录两个文件供使用
"""

# 生成gitbook目录树的文件
summarytree_filename = "CATALOG_FOR_GITBOOK.md"
# 一个课程目录文件
catalog_filename = "Catalog.md"
# 课程总结文件名
summary_filename = "Summary.md"
# 首页的README.md文件在生成的网站中的标题
readme_name = "Beego 微服务基础实战笔记介绍"

def get_catalog(folder):
	"""自动生成目录"""
	# 获取有哪几个章节列表
	dirs = os.listdir(folder)
	chapter_dir = []
	for path in dirs:
		whole_path = os.path.join(folder, path)
		if os.path.isdir(whole_path):
			if path.startswith("chapter"):
				chapter_dir.append(whole_path)
	chapter_dir.sort()

	# 初始化summarytree文件
	if os.path.exists(summarytree_filename):
		os.remove(summarytree_filename)
	with open(summarytree_filename, "a", encoding="utf-8") as f:
		f.write("# Summary\n\n")
		f.write("* [%s](./README.md)\n" % readme_name)
		f.write("* [课程目录](./Catalog.md)\n\n")

	# 初始化catalog文件
	if os.path.exists(catalog_filename):
		os.remove(catalog_filename)
	with open(catalog_filename, "a", encoding="utf-8") as f:
		f.write("# 课程目录\n\n")		

	# 写具体章节内容
	for chapter in chapter_dir:
		readme_path = os.path.join(chapter, "README.md")
		with open(readme_path, "r", encoding="utf-8") as f:
			chapter_name = f.readline().strip().replace("# ", "")
		filelist = os.listdir(chapter)
		try:
			filelist.remove("README.md")
		except Exception as e:
			pass
		try:
			filelist.remove("assets")
		except Exception as e:
			pass
		filelist.sort(key=return_index, reverse=False)
		# print(filelist)

		# 写summarytree文件内容
		with open(summarytree_filename, "a", encoding="utf-8") as f:
			f.write("* [{name}]({path})\n".format(name=chapter_name, path=chapter + "/README.md"))
			for cur_file in filelist:
				f.write("\t* [{name}]({path})\n".format(name=os.path.splitext(cur_file)[0], path=chapter + "/" + cur_file))

		# 写catalog文件内容
		with open(catalog_filename, "a", encoding="utf-8") as f:
			f.write("* ### [{name}]({path})\n".format(name=chapter_name, path=chapter))
			for cur_file in filelist:
				cur_file_name = os.path.splitext(cur_file)[0]
				f.write("\t* [{name}]({path})\n".format(name=cur_file_name, path=chapter + "/" + cur_file_name + ".html"))
	
	# 写课程总结summary链接
	with open(summarytree_filename, "a", encoding="utf-8") as f:		
		f.write("\n* [课程总结](./%s)\n" % summary_filename)

def return_index(filename):
	"""返回文件名的序号"""
	index1 = filename.find("-")
	index2 = filename.find(" ")
	return int(filename[index1 + 1 : index2])


if __name__ == '__main__':
	get_catalog("./")
	printDarkYellow("生成目录完成！\n\n")